package com.sendpo.zjx.sendpo.fragment;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMapUtils;
import com.amap.api.maps.model.LatLng;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.sendpo.zjx.sendpo.R;
import com.sendpo.zjx.sendpo.activity.StoreMainAllProduceActivity;
import com.sendpo.zjx.sendpo.activity.WebOnlineContentActivity;
import com.sendpo.zjx.sendpo.domain.MerchantHangyeDomain;
import com.sendpo.zjx.sendpo.domain.MerchantVideosDomain;
import com.sendpo.zjx.sendpo.net.HttpUrl;
import com.sendpo.zjx.sendpo.services.AmapLocationService;
import com.sendpo.zjx.sendpo.utils.Tools;
import com.sendpo.zjx.sendpo.utils.Xutils;
import com.zxl.library.DropDownMenu;

import org.xutils.common.Callback;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import me.zhanghai.android.materialratingbar.MaterialRatingBar;

/**
 * Created by 朱俊鑫 on 2018
 */

public class WatchStoreZensongFragment extends BaseWatchStoreFragment implements AMapLocationListener {

     @BindView(R.id.dropDownMenu)
    DropDownMenu dropDownMenu;
    private View dropcontent = null;
    public String[] headers = { "全部分类", "全城", "时间排序" };
    public LinearLayoutManager layoutManager;
    public String[] locationtype = { "全城", "地区" };
    public String[] ordertype = { "时间排序", "评价排序" };
    Unbinder unbinder;
    private View rootView;
   public String[] storetype =null;
     public int[] types = { DropDownMenu.TYPE_LIST_CITY, DropDownMenu.TYPE_LIST_CITY, DropDownMenu.TYPE_LIST_CITY };
    private RecyclerView recyclerview;
    private AmapLocationService amapLocationService;
   private  String city="";
   private  String area="";
   private  double longtiude=0.00;
   private  double latitude=0.00;

   public  int hangye_id=0;
   public int city_type=0;
   public int order_type=0;
    List<MerchantHangyeDomain.DataBean>  hangye;
    private int page=1;
    private  int pageSize=10;
     public int currentitem=0;
    RecylcerMessageAdaper adaper;
    private boolean lastloading=false;

    @Override
    public View initView() {
        View localView = View.inflate(this.mActivity, R.layout.fragment_watchstore_layout, null);
        ButterKnife.bind(localView, this.mActivity);
        return localView;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (rootView == null) {
            rootView = super.onCreateView(inflater, container, savedInstanceState);
            ButterKnife.bind(this, rootView);
            initComponent();
        }
        return rootView;
    }

    private void initComponent() {
        this.layoutManager = new LinearLayoutManager(this.mActivity, OrientationHelper.VERTICAL, false);
        getHangye();
        amapLocationService = new AmapLocationService(mActivity);
        amapLocationService.setmLocationOption(getDefaultAmapLocationOptions());
        amapLocationService.registerListener(WatchStoreZensongFragment.this);
        amapLocationService.start();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();

    }
    public AMapLocationClientOption getDefaultAmapLocationOptions() {
        AMapLocationClientOption mLocationOption = null;
        if (mLocationOption == null) {
            mLocationOption = new AMapLocationClientOption();
            //设置定位模式为AMapLocationMode.Hight_Accuracy，高精度模式。
            mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Battery_Saving);
            mLocationOption.setLocationCacheEnable(true);
              mLocationOption.setOnceLocation(true);
            mLocationOption.setOnceLocationLatest(false);
            //设置是否返回地址信息（默认返回地址信息）
            mLocationOption.setNeedAddress(true);
            //设置是否强制刷新WIFI，默认为true，强制刷1新。
            mLocationOption.setWifiScan(true);
            mLocationOption.setInterval(1000);
            //单位是毫秒，默认30000毫秒，建议超时时间不要低于8000毫秒。
            mLocationOption.setHttpTimeOut(20000);
        }
        return mLocationOption;
    }

     public void intquery(){
        Map<String,String> map=new HashMap<>();
       if(city_type==0){
           map.put("city",""+city);
       }else{
           map.put("city",""+city);
           map.put("area",""+area);
       }
       if(order_type==0){
           map.put("isComment","1");

       }else{
           map.put("isDatetime","1");
       }
         map.put("industry",""+hangye_id);
         map.put("page",""+page);
         map.put("pageSize",""+pageSize);
         System.out.println("****************************city:"+city);
         System.out.println("****************************area:"+area);
         System.out.println("****************************industry:"+hangye_id);
         Xutils.GET(HttpUrl.merchantsgetMerchantsVideo, map, new Callback.CommonCallback<String>() {
        @Override
        public void onSuccess(String result) {
            System.out.println("****************************result:"+result);
                Gson gson=new Gson();
            MerchantVideosDomain videoDomain= gson.fromJson(result,MerchantVideosDomain.class);
                  if(videoDomain.isFlag()){
                       if(videoDomain!=null&&videoDomain.getData()!=null&&videoDomain.getData().size()!=0){
                               if(adaper==null){
                               recyclerview.setAdapter(adaper=new RecylcerMessageAdaper(mActivity,videoDomain.getData()));
                                   recyclerview.setOnScrollListener(new RecyclerView.OnScrollListener() {
                                       @Override
                                       public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                                           super.onScrollStateChanged(recyclerView, newState);
                                           System.out.println("***********************onScrollStateChanged");
                                           if (currentitem == layoutManager.getItemCount() - 1 && newState == RecyclerView.SCROLL_STATE_IDLE) {
                                               System.out.println("***********************onScrollStateChanged"+layoutManager.getItemCount() );
                                               if (WatchStoreZensongFragment.this.page == 1 && adaper.dataBeans.size() >= 10 && lastloading == false) {
                                                   WatchStoreZensongFragment.this.page++;
                                                   append();
                                               }
                                           }
                                       }

                                       @Override
                                       public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                                           super.onScrolled(recyclerView, dx, dy);
                                           currentitem = layoutManager.findLastVisibleItemPosition();
                                       }
                                   });
                               }else{
                                 adaper.initRefresh(videoDomain.getData());
                               }
                       }else{
                           adaper.init();
                       }
                  }
        }
        @Override
        public void onError(Throwable ex, boolean isOnCallback) {

        }

        @Override
        public void onCancelled(CancelledException cex) {

        }

        @Override
        public void onFinished() {

        }
    });

    }
    public void append(){
        lastloading=true;
        Map<String,String> map=new HashMap<>();
        if(city_type==0){
            map.put("city",""+city);
        }else{
            map.put("city",""+city);
            map.put("area",""+area);
        }
        if(order_type==0){
            map.put("isComment","1");

        }else{
            map.put("isDatetime","1");
        }
        map.put("industry",""+hangye_id);
        map.put("page",""+page);
        map.put("pageSize",""+pageSize);
        System.out.println("****************************city:"+city);
        System.out.println("****************************area:"+area);
        System.out.println("****************************industry:"+hangye_id);
        Xutils.GET(HttpUrl.merchantsgetMerchantsVideo, map, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                lastloading=false;
                System.out.println("****************************result:"+result);
                Gson gson=new Gson();
                MerchantVideosDomain videoDomain= gson.fromJson(result,MerchantVideosDomain.class);
                if(videoDomain.isFlag()){
                    if(videoDomain!=null&&videoDomain.getData()!=null&&videoDomain.getData().size()!=0){
                        if(adaper==null){
                            recyclerview.setAdapter(adaper=new RecylcerMessageAdaper(mActivity,videoDomain.getData()));
                            recyclerview.setOnScrollListener(new RecyclerView.OnScrollListener() {
                                @Override
                                public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                                    super.onScrollStateChanged(recyclerView, newState);
                                    System.out.println("***********************onScrollStateChanged");
                                    if (currentitem == layoutManager.getItemCount() - 1 && newState == RecyclerView.SCROLL_STATE_IDLE) {
                                        System.out.println("***********************onScrollStateChanged"+layoutManager.getItemCount() );
                                        if (WatchStoreZensongFragment.this.page == 1 && adaper.dataBeans.size() >= 10 && lastloading == false) {
                                            WatchStoreZensongFragment.this.page++;
                                            append();
                                        }
                                    }
                                }

                                @Override
                                public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                                    super.onScrolled(recyclerView, dx, dy);
                                    currentitem = layoutManager.findLastVisibleItemPosition();
                                }
                            });
                        }else{
                            adaper.initAppend(videoDomain.getData());
                        }
                    }else{
//                        adaper.init();
                    }
                }
            }
            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                lastloading=false;
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });

    }
    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
              if(aMapLocation==null){
                  return;
              }
              city=aMapLocation.getCity();
              area=aMapLocation.getDistrict();
              longtiude=aMapLocation.getLongitude();
              latitude=aMapLocation.getLatitude();
        intquery();
    }


    public class RecylcerMessageAdaper extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
        public LayoutInflater inflater;
        public List<MerchantVideosDomain.DataBean> dataBeans;

        public RecylcerMessageAdaper(Context context, List<MerchantVideosDomain.DataBean> dataBeans) {
            this.inflater = LayoutInflater.from(context);
            this.dataBeans = dataBeans;
        }

        public int getItemCount() {
            return this.dataBeans.size();
        }

        public void onBindViewHolder(RecyclerView.ViewHolder paramViewHolder, int paramInt) {
            IndexHoler ih = (IndexHoler) paramViewHolder;
            final MerchantVideosDomain.DataBean videoDomain = dataBeans.get(paramInt);
             ih.startbar.setRating((Float.parseFloat(videoDomain.getCommentStar())));
             ih.guest_tv.setText(""+videoDomain.getCommentCount()+"人评论");
            ih.shopping_tv.setText("" + videoDomain.getMerchantsName());
            Glide.with(mActivity).load("" + videoDomain.getMerchantsImg()).asBitmap().animate(R.anim.fade_in).placeholder(R.color.default_lightgray).override(300, 300).into(ih.icon);
            ih.shexiangtou_iv.setOnClickListener(new View.OnClickListener() {
                public void onClick(View paramAnonymousView) {
                    Map<String, Object> map = new HashMap<>();
                    map.put("data", videoDomain);
                    Tools.redirectActivity(mActivity, WebOnlineContentActivity.class, map);
                }
            });
            ih.rootView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Map<String, Object> map = new HashMap<>();
                    map.put("merchantsId", videoDomain.getMerchantsId());
                    Tools.redirectActivity(mActivity, StoreMainAllProduceActivity.class, map);
                }
            });
            LatLng m_latLng = new LatLng(latitude, longtiude);
            LatLng latLng = new LatLng(Double.parseDouble(videoDomain.getLatitude()), Double.parseDouble(videoDomain.getLongitude()));
            int distance = (int) AMapUtils.calculateLineDistance(m_latLng, latLng);
            if (distance == 0) {
                ih.locationsize_tv.setText("就在附近");
            } else if (distance <= 5) {
                ih.locationsize_tv.setText("不足5m");
            } else {
                if (distance >= 1000) {
                    ih.locationsize_tv.setText("距离" + (distance / 1000) + "km");
                } else {
                    ih.locationsize_tv.setText("距离" + distance + "m");
                }

            }
        }

        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup paramViewGroup, int paramInt) {
            return new IndexHoler(this.inflater.inflate(R.layout.layout_business_listitem, paramViewGroup, false));
        }

        public class IndexHoler extends RecyclerView.ViewHolder {
            public ImageView icon;
            public TextView shopping_tv;
            public View rootView;
            public ImageView shexiangtou_iv;
            public TextView address;
            public TextView locationsize_tv;
            public MaterialRatingBar startbar;
            public TextView guest_tv;
            public IndexHoler(View itemView) {
                super(itemView);
                locationsize_tv = itemView.findViewById(R.id.locationsize_tv);
                address = itemView.findViewById(R.id.address);
                shopping_tv = itemView.findViewById(R.id.shopping_tv);
                this.rootView = itemView;
                this.shexiangtou_iv = itemView.findViewById(R.id.shexiangtou_iv);
                this.icon = itemView.findViewById(R.id.icon);
                startbar=itemView.findViewById(R.id.startbar);
                guest_tv=itemView.findViewById(R.id.guest_tv);
            }
        }

        public void initRefresh(List<MerchantVideosDomain.DataBean> domains) {
            this.dataBeans.removeAll(this.dataBeans);
            this.dataBeans.addAll(domains);
            notifyDataSetChanged();
        }

        public void initAppend(List<MerchantVideosDomain.DataBean> domains) {
            this.dataBeans.addAll(domains);
            notifyDataSetChanged();
        }
        public void init() {
            this.dataBeans.removeAll(this.dataBeans);
            notifyDataSetChanged();
        }
    }


    public void getHangye(){
        Xutils.GET(HttpUrl.getMerchantsIndustry, null, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                System.out.println("*********************************result"+result);
                       Gson gson=new Gson();
                MerchantHangyeDomain  domain=gson.fromJson(result, MerchantHangyeDomain.class);
                     if(domain.isFlag()){
                         hangye =domain.getData();
                         if(hangye!=null&&hangye.size()!=0){
                             storetype=new String[hangye.size()];
                             for(int i=0;i<hangye.size();i++){
                                 MerchantHangyeDomain.DataBean dataBean=hangye.get(i);
                               storetype[i]=dataBean.getName();
                             }
                             headers[0]=hangye.get(0).getName();
                             hangye_id=hangye.get(0).getId();
                             List<HashMap<String,Object>> arrayList = new ArrayList();
                             HashMap<String,Object> map1 = new HashMap();
                             map1.put(DropDownMenu.KEY,types[0]);
                             map1.put(DropDownMenu.VALUE, storetype);
                             map1.put(DropDownMenu.SELECT_POSITION,0);
                             HashMap<String,Object> map2 = new HashMap();
                             map2.put(DropDownMenu.KEY,types[1]);
                             map2.put(DropDownMenu.VALUE, locationtype);
                             map2.put(DropDownMenu.SELECT_POSITION,0);
                             HashMap<String,Object> map3 = new HashMap();
                             map3.put(DropDownMenu.KEY,types[2]);
                             map3.put(DropDownMenu.VALUE, ordertype);
                             map3.put(DropDownMenu.SELECT_POSITION,0);
                             arrayList.add(map1);
                             arrayList.add(map2);
                             arrayList.add(map3);
                             dropcontent = View.inflate(mActivity, R.layout.dropmenu_conentview, null);
                             recyclerview = dropcontent.findViewById(R.id.recyclerview);
                             recyclerview.setLayoutManager(layoutManager);
                             dropDownMenu.setDropDownMenu(Arrays.asList(headers), arrayList, dropcontent);
                             dropDownMenu.addMenuSelectListener(new DropDownMenu.OnDefultMenuSelectListener() {
                                 @Override
                                 public void onSelectDefaultMenu(int index, int pos, String clickstr) {
                                             switch (index){
                                                 case 0:
                                                     hangye_id=hangye.get(pos).getId();
                                                     break;
                                                 case 1:
                                                     city_type=pos;
                                                     break;
                                                 case 2:
                                                     order_type=pos;
                                                     break;
                                             }
                                     page=1;
                                     intquery();
                                 }
                             });
                             amapLocationService = new AmapLocationService(mActivity);
                             amapLocationService.setmLocationOption(getDefaultAmapLocationOptions());
                             amapLocationService.registerListener(WatchStoreZensongFragment.this);
                             amapLocationService.start();
                         }
                     }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });

    }
}

